import datetime

from sqlalchemy import BigInteger
from sqlalchemy.dialects.mysql import INTEGER, DATETIME

from shop.model import db
from shop.util.mylogger import KLogger


class UserBrowse(db.Model):
    __tablename__ = 'user_browse'

    id = db.Column(INTEGER(11), primary_key=True)
    user_id = db.Column(INTEGER(13), index=True)
    goods_id = db.Column(BigInteger, default=0, index=True)
    create_time = db.Column(DATETIME)

    @staticmethod
    def get_one_user_browse_record(user_id, page, page_size):
        page = int(page)
        page_size = int(page_size)
        user_id = int(user_id)
        # 查询总数
        total_num = db.session.query(UserBrowse).filter(UserBrowse.user_id == user_id).count()
        # 查询分页的所有记录
        user_browses = db.session.query(UserBrowse).filter(
            UserBrowse.user_id == user_id).order_by(
            UserBrowse.create_time.desc()).limit(page_size).offset((page - 1) * page_size).all()
        return user_browses, total_num

    @staticmethod
    def save_one_user_browse_record(user_id, goods_id):
        # 保存用户浏览记录
        user_id = int(user_id)
        goods_id = int(goods_id)
        KLogger.debug("保存用户浏览记录时的goods_id:")
        KLogger.debug(goods_id)
        one_user_browse = db.session.query(UserBrowse).filter(UserBrowse.user_id == user_id).filter(
            UserBrowse.goods_id == goods_id).first()
        if one_user_browse:
            one_user_browse.create_time = datetime.datetime.now()
        else:
            ub = UserBrowse()
            ub.user_id = user_id
            ub.goods_id = goods_id
            ub.create_time = datetime.datetime.now()
            db.session.add(ub)
        # 提交保存
        try:
            db.session.commit()
        except Exception as e:
            KLogger.error("保存或更新用户浏览记录报错：{}".format(str(e)))
            db.session.rollback()
            db.session.remove()
        finally:
            db.session.close()
